<template>
  <!-- 购物车页面 -->
  <div style="margin-top: 10px">
    <el-card class="box-card list" :body-style="{padding: '10px'}" style="width: 1000px; margin: auto">

      <h3 style="text-align: left; color: red">全部商品：{{productCount}}</h3>

      <div style="text-align: left">
        <span style="font-size: 13px">全选</span>
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"></el-checkbox>
      </div>

      <div style="line-height: 200px" v-if="productCount === 0">
        购物车还没有商品，快去购物吧
      </div>

      <el-descriptions direction="vertical" :column="6" border v-for="(item, index) in cartList" :key="index"
                       style="margin-bottom: 10px" v-if="productCount > 0">
        <el-descriptions-item :contentStyle="{width: '40px'}">
          <el-checkbox :key="index" @change="selectProduct($event, item)" :checked="false"></el-checkbox>
        </el-descriptions-item>
        <el-descriptions-item label="商品" :contentStyle="{width: '500px'}">
          <el-image style="width: 100px; height: 100px" :src="url"></el-image>
          <div class="cla-prod">{{ item.productName }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="单价">{{ item.productPrice }}</el-descriptions-item>
        <el-descriptions-item label="数量">
          <el-input-number size="mini" v-model="item.productNum" @change="handleChange($event, item.productId)"
                           style="width: 120px" :min="1"></el-input-number>
        </el-descriptions-item>
        <el-descriptions-item label="小计">{{ item.totalPrice }}</el-descriptions-item>
        <el-descriptions-item label="操作">
          <el-link type="danger">删除</el-link>
          <br>
          <el-link type="primary">加入收藏</el-link>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="box-card" :body-style="{padding: '10px'}" style="width: 1000px; margin: auto">
      <div style="text-align: right;">
        <span style="font-size: 12px; font-weight: 600">共选择{{selectProductNum}}件商品&nbsp;&nbsp;总价：</span>
        <span style="font-weight: 600; color: red">￥{{selectProductCountPrice}}</span>
        <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
        <el-button type="danger" @click="goPay">去结算</el-button>
      </div>
    </el-card>

    <el-card class="box-card" :body-style="{padding: '10px'}" style="margin-top: 10px">
      猜你喜欢，为你推荐
      <br>
      <br>
    </el-card>

    <div ref="alipayWap" v-html="alipayForm" style="display: none"></div>
  </div>
</template>

<script>
  import {get, post} from '@/api/http.js'

  export default {
    name: "cart",

    // 钩子函数，页面加载就执行
    mounted() {
      this.getCartList();
    },

    // 数据区
    data() {
      return {
        isIndeterminate: false,
        size: '',
        url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',

        // 列表全选
        checkAll: false,

        // 购物车数据清单
        cartList: [],

        // 购物车商品总数
        productCount: 0,

        // 购物车操作数量
        addCartForm: {
          userId: '',
          productId: '',
          productNum: null
        },

        // 选中的商品集合
        selectProducts: [],

        // 结算选中商品的数量
        selectProductNum: 0,
        selectProductCountPrice: 0.00,

        // 支付宝支付表单
        alipayForm: '',

        // 结算请求参数
        payOrder: {
          vipId: '',
          list: [],
          remake: ''
        },
      }
    },

    // 方法区
    methods: {

      // 结算
      goPay() {
        // 给请求对象赋值
        this.payOrder.vipId = localStorage.getItem('authToken');
        this.payOrder.list = this.selectProducts;
        // 发起请求
        post('/pay/alipay/do', this.payOrder)
          .then(res => {
            this.alipayForm = res.data;
            // 防抖避免重复支付
            this.$nextTick(() => {
              // 提交支付表单
              this.$refs.alipayWap.children[0].submit();
            })
          })
          .catch(err => {
          })

      },

      // 购物车选中计算
      selectProduct: function (val, item) {
        if (val === true) {
          this.selectProducts.push(item);
        } else {
          this.selectProducts.splice(this.selectProducts.indexOf(item), 1);
        }

        console.info(this.selectProducts);

        // 设置选中的商品数量
        this.selectProductNum = this.selectProducts.length;

        // 遍历选中的商品，计算总价
        let countPrice = 0.00;
        this.selectProducts.forEach(prod => {
          countPrice += prod.totalPrice;
        });
        this.selectProductCountPrice = countPrice;
      },

      // 购物车全选
      handleCheckAllChange(val) {
        // this.checkedCities = val ? cityOptions : [];
        // this.isIndeterminate = false;
      },

      // 购物车商品数量改变
      handleChange(val, bizId) {
        // 获取、组装参数
        let userId = localStorage.getItem('authToken');
        if (userId === null || userId === '' || userId === undefined || userId === 'undefined') {
          this.$router.push("/login");
        }
        this.addCartForm.userId = userId;
        this.addCartForm.productId = bizId;
        this.addCartForm.productNum = val;
        // 发起改变请求
        post('/retail/product/addCart2', this.addCartForm)
          .then(res => {
            this.$message({
              message: '添加成功',
              type: 'success'
            });

            // 重新加载购物车
            this.getCartList();

            // 计算总价
            this.reloadCart(bizId);
          })
          .catch(err => {
            this.$message({
              message: '操作失败',
              type: 'error'
            });
          })
          .finally(() => {
          });
      },

      // 计算总价
      reloadCart(bizId) {
        // 在选中的商品列表，对比当前操作的商品ID，如果一样说明改动的是选中的商品
        let isCheck = false;
        this.selectProducts.forEach(prod => {
          if (prod.productId === bizId) {
            isCheck = true;
            this.selectProducts.splice(this.selectProducts.indexOf(prod), 1);
          }
        });

        // 如果是改变的是选中的数据，则重新加入当前这个数据对象
        if (isCheck) {
          this.cartList.forEach(prod => {
            if (prod.productId === bizId) {
              console.info(prod.totalPrice);
              this.selectProducts.push(prod);
            }
          });

          // 遍历选中的商品，计算总价
          let countPrice = 0.00;
          this.selectProducts.forEach(prod => {
            countPrice += prod.totalPrice;
          });
          this.selectProductCountPrice = countPrice;
        }
      },

      // 获取购物车清单
      getCartList() {
        let userId = localStorage.getItem('authToken');
        get('/retail/product/getCart/' + userId, '')
          .then(res => {
            this.cartList = res.data;
            this.productCount = res.data.length;
          })
          .catch(err => {
            console.info("===cart err===");
            console.info(err);
          })
      }
    }
  }
</script>

<style scoped>
  .list ul li {
    list-style-type: none
  }

  .cla-prod {
    width: 300px;
    margin-left: 111px;
    margin-top: -100px;
    float: left;
  }

</style>
